﻿#include "navigationbar.h"
#include <QVBoxLayout>
#include <QSizePolicy>
#include <QPixmap>
#include <QIcon>

NavigationBar::NavigationBar(QWidget *parent)
    : QWidget{parent}
{
    m_mainLayout = new QVBoxLayout;
    m_mainLayout->setContentsMargins(20,20,20,10);
    m_mainLayout->setSpacing(10);
    m_mainLayout->addSpacerItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));
    this->setLayout(m_mainLayout);
}

void NavigationBar::addPage(QWidget *page, QPixmap sepix, QPixmap unsepix,
                            QPixmap unsefloatingpix, QString text, bool defaultSe) {
    NavigationPushButton* config = new NavigationPushButton(this);
    config->setMinimumHeight(40);
    config->setselectPix(sepix);
    config->setunSelectPix(unsepix);
    config->setunSelectFloatingPix(unsefloatingpix);
    config->setText(text);
    config->setisSelected(defaultSe);
    m_buttons.insert(text, config);
    m_pages.insert(text, page);
    connect(config, &NavigationPushButton::clicked, this, &NavigationBar::onCurrSelectBtnChange);

    int index = m_mainLayout->count() - 1;
    m_mainLayout->insertWidget(index, config);
}

void NavigationBar::startRun()
{
    if(m_currSelectName.isEmpty()) {
        QString sestr = static_cast<QPushButton*>(m_mainLayout->itemAt(0)->widget())->text();
        m_currSelectName = sestr;
    }

    m_buttons[m_currSelectName]->setisSelected(true);
    m_buttons[m_currSelectName]->update();

    emit selectPageChange(m_currSelectName, m_pages[m_currSelectName]);
}

void NavigationBar::onCurrSelectBtnChange()
{
    QPushButton* btn = static_cast<QPushButton*>(QObject::sender());
    if(!btn)
        return;

    QString strtext = btn->text();
    if(strtext == m_currSelectName)
        return;

    m_buttons[m_currSelectName]->setisSelected(false);
    m_buttons[m_currSelectName]->update();

    m_currSelectName = strtext;

    m_buttons[m_currSelectName]->setisSelected(true);
    m_buttons[m_currSelectName]->update();

    emit selectPageChange(m_currSelectName, m_pages[m_currSelectName]);
}

void NavigationBar::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    painter.save();
    painter.setPen(Qt::NoPen);
    QColor transparentColor(255, 255, 255);
    painter.setBrush(transparentColor);
    painter.drawRoundedRect(rect(), 15, 15);
    painter.restore();
}

